<template>
	<view class="container">
		<view class="">
			<view class="project-switcher" v-if="projectshow">
				<picker class="project-picker" @change="switchProject" :value="projectIndex" :range="projectList"
					range-key="title">
					<view class="picker">
						当前项目：{{currentProjectTitle}}
						<view class="picker-icon">▼</view>
					</view>
				</picker>
			</view>

			<!-- 培训分数 -->
			<van-field name="rate" label="培训分数">
				<template #input>
					<van-rate v-model="trainingScore" @change="handleTrainingScoreChange" />
				</template>
			</van-field>

			<!-- 讲师分数 -->
			<van-field name="rate" label="讲师分数">
				<template #input>
					<van-rate v-model="teacherScore" @change="handleTeacherScoreChange" />
				</template>
			</van-field>

			<!-- 反馈图片 -->
			<view class="feedback-image-section">
				<view class="section-label">反馈图片</view>
				<view class="image-uploader-container">
					<view class="image-uploader">
						<view class="image-preview" v-for="(item, index) in feedbackImg" :key="index"
							@click="previewImage(index)">
							<image :src="item" mode="aspectFill" class="preview-image"></image>
							<view class="delete-btn" @click.stop="deleteImage(index)">×</view>
						</view>
						<view class="upload-btn" @click="chooseImage" v-if="feedbackImg.length < 9">
							<text>+</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 账号所属地 -->
			<!-- <van-field name="radio" label="账号所属地">
				<template #input>
					<van-radio-group v-model="location" @change="changelocation" direction="horizontal">
						<van-radio name="0">海外</van-radio>
						<van-radio name="1">青岛</van-radio>
					</van-radio-group>
				</template>
			</van-field> -->
		</view>

		<!-- 反馈内容 -->
		<van-cell-group inset>
			<van-field v-model="feedbackInfo" @input="handleFeedbackInput" rows="2" autosize label="反馈内容"
				type="textarea" maxlength="50" placeholder="请输入留言" show-word-limit />
		</van-cell-group>

		<div style="margin: 16px;">
			<van-button round block type="primary" :loading="loading"
				:disabled="loading || (!currentProjectId && !selectedProjectId)" @click="submitForm">
				提交反馈
			</van-button>
		</div>
	</view>
</template>

<script>
	import {
		trainingFeedback,
		qingdaoProject
	} from "../../utils/getDate.js"

	export default {
		data() {
			return {
				projectshow: true,
				trainingScore: 0,
				teacherScore: 0,
				feedbackInfo: "",
				projectId: "", // 从options获取的id
				selectedProjectId: "", // picker选择的id
				currentProjectId: "", // 当前选中的项目ID
				currentProjectTitle: "请选择项目", // 显示的项目名称
				location: "1",
				userId: "",
				loading: false,
				feedbackImg: [], // 用于显示的文件列表
				uploadedImages: [], // 存储已上传的服务器URL
				projectList: [], // 项目列表数据
				projectIndex: 0, // picker当前选中索引
			}
		},
		onLoad(options) {

			this.userId = uni.getStorageSync("userinfo").id;

			if (options.id) {
				// 如果有传入的项目ID，直接使用
				this.projectId = options.id;
				this.currentProjectId = options.id;
				// 如果有传入项目名称，也一并设置
				if (options.name) {
					this.currentProjectTitle = decodeURIComponent(options.name);
				}
				this.projectshow = false
			} else {
				// 没有传入ID，获取项目列表
				this.getProjectList();
			}
		},
		methods: {
			handleFeedbackInput(e) {
				// ✅ 正确：赋值字符串
				this.feedbackInfo = e.detail; // 或 e.detail.value，取决于 Vant 版本
			},
			// 处理培训分数变化
			handleTrainingScoreChange(e) {
				console.log('培训分数变化:', e.detail);
				this.trainingScore = e.detail;
			},

			// 处理讲师分数变化
			handleTeacherScoreChange(e) {
				console.log('讲师分数变化:', e.detail);
				this.teacherScore = e.detail;
			},
			changelocation(e) {
				console.log('培训分数变化:', e.detail);
				this.location = e.detail;
			},

			// 切换项目
			switchProject(e) {
				const index = e.detail.value;
				this.projectIndex = index;
				this.currentProjectId = this.projectList[index].projectId;
				this.currentProjectTitle = this.projectList[index].title;
				this.selectedProjectId = this.currentProjectId; // 同步到selectedProjectId
			},

			// 获取项目列表
			async getProjectList() {
				try {
					const res = await qingdaoProject({
						userId: this.userId
					});
					if (res.state === 'ok') {
						this.projectList = res.data.map(item => ({
							title: item.title,
							projectId: item.id
						}));

						// 默认选中第一个项目
						if (this.projectList.length > 0) {
							this.currentProjectId = this.projectList[0].projectId;
							this.currentProjectTitle = this.projectList[0].title;
							this.selectedProjectId = this.currentProjectId;
							this.projectIndex = 0;
						}
					}
				} catch (error) {
					console.error('获取项目列表失败:', error);
					uni.showToast({
						title: '获取项目列表失败',
						icon: 'none'
					});
				}
			},

			// 选择图片
			chooseImage() {
				const maxCount = 9 - this.feedbackImg.length;
				if (maxCount <= 0) return;

				uni.chooseImage({
					count: maxCount,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.uploadImages(res.tempFilePaths);
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},

			// 删除图片
			deleteImage(index) {
				this.feedbackImg.splice(index, 1);
				this.uploadedImages.splice(index, 1);
			},

			// 图片上传方法
			async uploadImages(tempFilePaths) {
				uni.showLoading({
					title: '图片上传中...',
					mask: true
				});

				try {
					const uploadTasks = tempFilePaths.map(filePath => {
						return new Promise((resolve, reject) => {
							uni.uploadFile({
								url: 'https://applet.eapchina.net/api/sleep/uploadFile',
								filePath,
								name: 'file',
								success: (uploadRes) => {
									try {
										const data = JSON.parse(uploadRes.data);
										data.imgUrl ? resolve({
											localUrl: filePath,
											serverUrl: data.imgUrl
										}) : reject(new Error('上传失败'));
									} catch (e) {
										reject(e);
									}
								},
								fail: reject
							});
						});
					});

					const results = await Promise.all(uploadTasks);

					this.feedbackImg = [...this.feedbackImg, ...results.map(item => item.localUrl)];
					this.uploadedImages = [...this.uploadedImages, ...results.map(item => item.serverUrl)];

					uni.showToast({
						title: '照片上传成功',
						icon: 'success'
					});
				} catch (error) {
					console.error('图片上传失败:', error);
					uni.showToast({
						title: '图片上传失败，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 提交表单
			async submitForm() {
				if (this.loading) return;

				// 表单验证
				const validations = [{
						condition: this.trainingScore === 0,
						message: '请为培训评分'
					},
					{
						condition: this.teacherScore === 0,
						message: '请为讲师评分'
					},
					{
						condition: !this.currentProjectId && !this.selectedProjectId,
						message: '请选择项目'
					},
					// {
					// 	condition: !this.feedbackInfo.trim(),
					// 	message: '请输入反馈内容'
					// }
				];

				for (const {
						condition,
						message
					}
					of validations) {
					if (condition) {
						uni.showToast({
							title: message,
							icon: 'none'
						});
						return;
					}
				}

				this.loading = true;

				try {
					const res = await trainingFeedback({
						training_score: this.trainingScore,
						teacher_score: this.teacherScore,
						feedback_img: this.uploadedImages,
						feedback_info: this.feedbackInfo,
						project_id: this.currentProjectId || this.selectedProjectId,
						location: this.location,
						teacher_id: this.teacherId,
						name: uni.getStorageSync("userinfo").name
					});

					if (res.state === "ok") {
						uni.showToast({
							title: '提交成功',
							icon: 'success',
							duration: 1500
						});

						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						throw new Error(res.message || '提交失败');
					}
				} catch (error) {
					console.error('提交失败:', error);
					uni.showToast({
						title: error.message || '提交失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			}
		}
	}
</script>
<style scoped>
	/* 项目选择器样式 */
	.project-switcher {
		margin: 30rpx 0;
	}

	.project-picker {
		background: #fff;
		border-radius: 20rpx;
		padding: 20rpx 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		font-size: 28rpx;
		color: #4b5563;
	}

	.picker {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.picker-icon {
		font-size: 24rpx;
		color: #9ca3af;
		margin-left: 20rpx;
	}

	/* 原有样式保持不变，新增以下样式 */

	.project-switcher {
		background: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.project-list {
		white-space: nowrap;
		width: 100%;
	}

	.project-item {
		display: inline-block;
		padding: 10rpx 30rpx;
		margin-right: 20rpx;
		background: #f3f4f6;
		border-radius: 30rpx;
		font-size: 28rpx;
		color: #4b5563;
	}

	.project-item.active {
		background: #3b82f6;
		color: #fff;
		font-weight: bold;
	}

	.container {
		padding-bottom: 30px;
	}

	.image-uploader {
		display: flex;
		flex-wrap: wrap;
	}

	.upload-btn {
		width: 150rpx;
		height: 150rpx;
		border: 1px dashed #ccc;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		border-radius: 8rpx;
	}

	.upload-btn text {
		font-size: 50rpx;
		color: #666;
	}

	.image-preview {
		width: 150rpx;
		height: 150rpx;
		position: relative;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		border-radius: 8rpx;
		overflow: hidden;
	}

	.preview-image {
		width: 100%;
		height: 100%;
	}

	.delete-btn {
		position: absolute;
		right: 0;
		top: 0;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		border-bottom-left-radius: 8rpx;
	}
	/* 图片上传区域样式 */
	.feedback-image-section {
	  margin: 30rpx 0;
	  padding: 0 30rpx;
	}
	
	.section-label {
	  font-size: 28rpx;
	  color: #646566;
	  margin-bottom: 20rpx;
	  padding-left: 10rpx;
	}
	
	.image-uploader-container {
	  width: 100%;
	}
	
	.image-uploader {
	  display: flex;
	  flex-wrap: wrap;
	  margin-right: -20rpx;
	}
	
	.image-preview {
	  width: 200rpx;
	  height: 200rpx;
	  position: relative;
	  margin-right: 20rpx;
	  margin-bottom: 20rpx;
	  border-radius: 12rpx;
	  overflow: hidden;
	  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}
	
	.preview-image {
	  width: 100%;
	  height: 100%;
	  display: block;
	}
	
	.delete-btn {
	  position: absolute;
	  right: 0;
	  top: 0;
	  width: 50rpx;
	  height: 50rpx;
	  background-color: #ff4444;
	  color: white;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  border-bottom-left-radius: 12rpx;
	  font-size: 36rpx;
	  font-weight: bold;
	  z-index: 2;
	}
	
	.upload-btn {
	  width: 200rpx;
	  height: 200rpx;
	  border: 2rpx dashed #ccc;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  margin-right: 20rpx;
	  margin-bottom: 20rpx;
	  border-radius: 12rpx;
	  background-color: #f7f7f7;
	}
	
	.upload-btn text {
	  font-size: 60rpx;
	  color: #999;
	  margin-top: -10rpx;
	}
</style>